package com.marmot.cloud.framework.core.pager;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import java.util.ArrayList;
import java.util.List;

@Data
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
@Schema(description = "分页信息模型")
public class PageHelper<T> {
    @Schema(description = "查询条件")
    private T query;
    @Schema(description = "分页条件")
    private Pager pager;
    @Schema(description = "排序条件")
    private Sorter sorter;

    public Pageable builder() {
        List<Sort.Order> orders = new ArrayList();
        if (sorter != null && sorter.getOrders() != null) {
            sorter.getOrders().forEach(vo -> {
                if (StrUtil.equalsIgnoreCase(vo.getDirection(), "asc")) {
                    orders.add(new Sort.Order(Sort.Direction.ASC, vo.getProperty()));
                } else {
                    orders.add(new Sort.Order(Sort.Direction.DESC, vo.getProperty()));
                }
            });
        }
        if (pager == null) {
            pager = new Pager();
        }
        // 设置分页
        return PageRequest.of(pager.getPageNum() - 1, pager.getPageSize(), Sort.by(orders));
    }

    /**
     * 转换成指定泛型的分页对象
     *
     * @param tClass 目标类型
     * @param <M>    目标泛型
     * @return
     */
    public <M> PageHelper<M> converter(Class<M> tClass) {
        PageHelper<M> pageHelper = new PageHelper<>();
        pageHelper.setSorter(this.getSorter());
        pageHelper.setPager(this.getPager());
        pageHelper.setQuery(BeanUtil.copyProperties(this.getQuery(), tClass));
        return pageHelper;
    }

}
